package com.java.exer_2;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * @author luzhikun
 * @date &{DATE}-12:16
 */
public class CountDown extends JFrame {
    JButton jButton;
    JLabel jLabel;
    int time = 60;

    public CountDown() {
        FlowLayout fl = new FlowLayout(FlowLayout.CENTER);
        this.setLayout(fl);
        //为按钮jButton添加监听器，实现点击时倒计时重新开始
        jButton = new JButton("重新开始");
        jButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent arg0) {
                dispose();//关闭当前窗口
                new CountDown();//新建一个窗口
            }

        });
        //匿名创建一个线程内部类来实现时间倒计时，这是整篇代码的核心
        jLabel = new JLabel();

        new Thread() {
            public void run() {
                while (time > 0) {
                    time--;
                    if (time < 6) {//当时间只剩5秒时闪红
//                        jLabel.setFont("黑体",Font.BOLD);
                        jLabel.setForeground(Color.RED);
                    }
                    jLabel.setText(time + "秒");
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }

        }.start();

        this.add(jButton);
        this.add(jLabel);
        this.setTitle("倒计时");
        this.setSize(800, 700);
        this.setLocationRelativeTo(null);
        this.setResizable(true);
        this.setVisible(true);
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {
        new CountDown();

    }

}

